package it.uniroma2.reasoner.utils.Graph;

import java.util.HashMap;
import java.util.LinkedList;
import java.util.Queue;

import org.json.simple.JSONArray;
import org.json.simple.JSONObject;

import edu.uci.ics.jung.graph.DirectedSparseMultigraph;
import edu.uci.ics.jung.graph.Graph;

public class GraphUtils {
	
	public static Graph<String,String> BreabreadthFirstSearch(Graph<String,String> graph, String vertex){
		
		Graph<String, String> newGraph = new DirectedSparseMultigraph<String, String>();
		
		int count =0;
		Queue<String> queue = new LinkedList<String>();
		queue.add(vertex);
		while(!queue.isEmpty()) {
			String node = (String)queue.remove();
			newGraph.addVertex(node);
			for(String successor :graph.getSuccessors(node)){
				newGraph.addVertex(successor);
				newGraph.addEdge(String.valueOf(count), node, successor);
				count++;
				queue.add(successor);
			}
		
		}
		return newGraph;
		
	}
	
public static String BreabreadthFirstSearchHistoryTriple(Graph<String,String> graph, String vertex){
		
		String builder = "";
		
		JSONArray nodes = new JSONArray();
		
		HashMap<String,Integer> map = new HashMap<String,Integer>();
		int count2=0;
		
		Graph<String, String> newGraph = new DirectedSparseMultigraph<String, String>();
		
		int count =0;
		Queue<String> queue = new LinkedList<String>();
		queue.add(vertex);
		
		map.put(vertex, count2);
		while(!queue.isEmpty()) {
			String node = (String)queue.remove();
			
			
			if(graph.getSuccessors(node).size() > 0 ){
				JSONObject nodo = new JSONObject();
				nodo.put("searched_node", node);
				nodes.add(nodo);
				builder = builder +"Searched node: "+node+"\n";
			}
			
			newGraph.addVertex(node);
//			
//			if(graph.getSuccessors(node).size() >0){
//				JSONObject nodo = new JSONObject();
//				builder = builder +"Node: "+node+" is generated by \n";
//			}
			for(String successor :graph.getSuccessors(node)){
				newGraph.addVertex(successor);
				
				newGraph.addEdge(String.valueOf(count), node, successor);
				count++;
				queue.add(successor);
				if(!map.containsKey(successor)){
					JSONObject nodo = new JSONObject();
					nodo.put("geenrated", successor);
					nodes.add(nodo);
					
					map.put(successor, count2);
					builder = builder +count2+": "+successor+"\n";
					count2++;
				}
				else{
					JSONObject nodo = new JSONObject();
					nodo.put("geenrated", successor);
					nodes.add(nodo);
					builder = builder +map.get(successor)+": "+successor+"\n";
				}
			}
		
		}
		if(builder.toString().equals("")){
			builder = builder +vertex+"\n";
			JSONObject nodo = new JSONObject();
			nodo.put("searched_node", vertex);
			nodes.add(nodo);
			return nodes.toJSONString();
		}
		return nodes.toJSONString();
		
	}

}